package cn.quevo.core.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

/**
 * Bean转换
 *
 * @author July july_sky@foxmail.com
 * @version 1.0
 * @date 2018-03-09 16:26:40
 * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
 * @return
 */
public abstract class BeanUtils extends org.springframework.beans.BeanUtils {

    private final static Logger log = LoggerFactory.getLogger(BeanUtils.class);

    /**
     * 将Bean转换成Map
     *
     * @param bean
     * @return
     * @author July july_sky@foxmail.com
     * @date 2018-03-09 16:26:50
     * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
     * @version 1.0
     */
    public static Map<String, String> objectToMap(Object bean) {
        try {
            return org.apache.commons.beanutils.BeanUtils.describe(bean);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 将Map转换成Bean
     *
     * @param bean
     * @param properties
     * @return
     * @author July july_sky@foxmail.com
     * @date 2018-03-09 16:26:57
     * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
     * @version 1.0
     */
    public static Boolean mapToObject(Object bean, Map<String, Object> properties) {
        try {
            org.apache.commons.beanutils.BeanUtils.populate(bean, properties);
            return true;
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 属性复制，排除null值
     * 
     * @author July july_sky@foxmail.com
     * @date 2018年3月18日 下午9:49:59
     * @param source
     * @param target
     * @throws BeansException
     */
    public static void copyPropertiesExcludeNull(Object source, Object target,@Nullable String... ignoreProperties) throws BeansException {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");

        Class<?> actualEditable = target.getClass();
        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
        boolean invoke = true;
        for (PropertyDescriptor targetPd : targetPds) {
            Method writeMethod = targetPd.getWriteMethod();
            invoke = writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()));
            if(!invoke) {
                continue;
            }
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if(sourcePd == null) {
                continue;
            }
            Method readMethod = sourcePd.getReadMethod();
            invoke = readMethod != null && 
                    ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType());
            if(!invoke) {
                continue;
            }
            try {
                if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                    readMethod.setAccessible(true);
                }
                Object value = readMethod.invoke(source);
                if(value == null) {
                    continue;
                }
                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                    writeMethod.setAccessible(true);
                }
                writeMethod.invoke(target, value);
            }
            catch (Throwable ex) {
                throw new FatalBeanException(
                        "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
            }
        }
    }
}